// pages/promoter/promoter.js
const userUtils = require("../../utils/user");
const validate = require('../../utils/validate');
const common = require('../../utils/common');
const wxp = require('../../utils/wxp.js');
const {
  getHomeData
} = require('../../services/home');
const {
  shopGenerate
} = require('../../services/shop');
const {
  getPromoterStats
} = require('../../services/promoter');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareCodeInfo: {}, //分享门店二维码信息
    codeMenus: [{
        icon: '/images/index/code_md.png',
        name: '下载\n门店二维码',
      },
      {
        icon: '/images/index/code_mdhb.png',
        name: '下载\n门店海报',
      }, {
        icon: '/images/index/code_tghb.png',
        name: '下载\n推广海报',
      }
    ],
    servicesMenus: [{
        name: '我的账单',
        icon: '/images/index/index_myorder.png',
        src: '/pages/bill/index'
      },
      {
        name: '门店录入',
        icon: '/images/index/index_shopInput.png',
        src: '/pages/add-store/index'
      }, {
        name: '推广海报',
        icon: '/images/index/index_tghb.png',
        src: '/pages/promotePage/index'
      },
      {
        name: '我的分销',
        icon: '/images/index/index_wdsy.png',
        src: '/pages/myPromoter/index'
      },
      {
        name: '联系客服',
        icon: '/images/index/index_lxkf.png',
        src: '/pages/contactService/index'
      }
    ],
    isLogin: false,
    minPickup: 100,
    withdrawEnable: false, //是否可以提现
    pageScrollTop: 0,
    isCodeViewShow: false,
    containerTouchmove: '',
    profitList: [{
      title: '今日收益',
      value: '0'
    }, {
      title: '预估收益',
      value: '0'
    }, {
      title: '当月收益',
      value: '0'
    }, {
      title: '累计收益',
      value: '0'
    }, {
      title: '当月销售',
      value: '0'
    }, {
      title: '总销售额',
      value: '0'
    }],
    statsInfo: {},
    homeData: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu({});
    wx.hideHomeButton({});
    // 获取数据
    this.onPullDownRefresh();
  },

  // 获取数据
  requestToGetHomdeData(pullDownRefresh) {
    let requestList = [];
    //首页数据
    requestList.push(getHomeData());
    // 收益
    requestList.push(getPromoterStats());
    Promise.all(requestList).then(results => {
      // 首页数据
      this.handleHomeData(results[0]);
      //处理收益数据
      this.handlePromoterStats(results[1]);
      if (pullDownRefresh) {
        wx.stopPullDownRefresh({});
      }
    }).catch(err => {
      if (pullDownRefresh) {
        wx.stopPullDownRefresh({});
      }
      common.log(err);
    });
  },

  // 处理返回的平铺广告
  handleHomeData(res) {
    const userInfo = userUtils.getUserInfo()
    const isLogin = userInfo && userInfo.login
    userUtils.updateUserInfo({
      shopVo: res.data.shopVo
    })
    let homeData = {}
    if (res.data.fakePage && !isLogin) {
      homeData = {
        ...res.data
      }
    } else {
      homeData = res.data
    }
    this.setData({
      homeData,
      isLogin,
    }, this.checkWithdrawEnable)
  },

  // 处理收益数据
  handlePromoterStats(res) {
    //今日收益
    let jrtjItem = this.data.profitList[0];
    jrtjItem.value = res.data.todayIncome;
    //预估收益
    let ygsyItem = this.data.profitList[1];
    ygsyItem.value = res.data.exceptedIncome;
    //当月收益
    let dysyItem = this.data.profitList[2];
    dysyItem.value = res.data.monthIncome;
    //累计收益
    let ljsyItem = this.data.profitList[3];
    ljsyItem.value = res.data.allIncome;
    //当月销售
    let dyxsItem = this.data.profitList[4];
    dyxsItem.value = res.data.monthSoldAmount;
    //总销售额
    let zxseItem = this.data.profitList[5];
    zxseItem.value = res.data.soldAmount;
    this.setData({
      profitList: this.data.profitList,
      statsInfo: res.data
    });
  },

  checkWithdrawEnable: function () {
    const {
      homeData
    } = this.data
    const withdrawEnable = homeData.totalAmount >= this.data.minPickup
    this.setData({
      withdrawEnable
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.requestToGetHomdeData(true);
  },
  goWidthdraw: function () {
    if (this.isFakePage()) return;
    const {
      homeData
    } = this.data
    if (!this.data.withdrawEnable) return
    wx.navigateTo({
      url: `/pages/withdraw/index?total=${homeData.totalAmount}&bankCardNo=${homeData.shopVo.bankCardNo}`
    })
  },
  // 是否已经登录
  isFakePage() {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/index'
      })
      return true;
    } else {
      return false;
    }
  },

  // 常用服务
  goDetial: function (e) {
    if (this.isFakePage()) return;
    let index = e.currentTarget.dataset.index;
    let item = this.data.servicesMenus[index];
    if (item.name == "我的分销") {
      let data = {
        realname: '我',
        shopId: this.data.homeData.shopVo.id,
        navTitle: '我的分销'
      }
      wx.navigateTo({
        url: '../myPromoter/index?optionsData=' + common.jsonStringify(data),
      })
    } else {
      wx.navigateTo({
        url: item.src
      });
    }
  },
  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    var topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () {},
  // 活动规则
  onDownloadCode() {
    this.setData({
      isCodeViewShow: true,
      containerTouchmove: 'preventTouchMove'
    })
  },
  // 取消规则弹窗
  onCodeBg() {
    this.setData({
      isCodeViewShow: false,
      containerTouchmove: ''
    })
  },
  //获取海报连接
  /**
    path 跳转路径
    platform 生成的二维码平台
    type 分享类型，1邀请团长海报，2首页海报
   */
  getShopPoster({
    path,
    platform,
    type
  }) {
    let params = {
      path: path,
      platform: platform,
      type: type,
    }
    shopGenerate(params).then(res => {
      this.setData({
        shareCodeInfo: {
          ...this.data.shareCodeInfo,
          ...{
            ['icon' + type]: res.data
          }
        }
      });
      // 保存
      this.onSavePoster(this.data.shareCodeInfo['icon' + type], type, this.data.shareCodeInfo['filePath' + type])
    }).catch(err => {
      common.log(err);
    })
  },
  // 保存海报
  /**
   * 
   * @param {*} icon 下载地址 
   * @param {*} type 海报分享类型
   * @param {*} filePath 可以保存的path
   */
  onSavePoster(icon, type, filePath) {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/index'
      })
      return
    }
    if (filePath) {
      this.saveToAlbum(filePath);
      return
    }
    common.wxDownloadFile(icon).then(res => {
      this.setData({
        shareCodeInfo: {
          ...this.data.shareCodeInfo,
          ...{
            ['filePath' + type]: res
          }
        }
      })
      this.saveToAlbum(this.data.shareCodeInfo['filePath' + type]);
    }).catch(err => {
      common.log(err);
    })
  },
  // 点击二维码
  onCodeItem(e) {
    if (e.detail.index == 0) {
      // 门店二维码
      this.onSavePoster(this.data.homeData.shopVo.codeUrl, 'er', this.data.shareCodeInfo['filePath' + 'er'])
    } else if (e.detail.index == 1) {
      // 门店海报
      this.getShopPoster({
        path: 'pages/index/index',
        platform: '1',
        type: '2'
      });
    } else if (e.detail.index == 2) {
      // 推广海报
      this.getShopPoster({
        path: 'pages/index/index',
        platform: '1',
        type: '1'
      });
    }
    this.onCodeBg();
  },
  //保存到相册
  saveToAlbum: function (filePath) {
    //获取权限
    if (wx.saveImageToPhotosAlbum) {
      wxp.getSetting().then(res => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wxp.authorize({
            scope: 'scope.writePhotosAlbum'
          }).then(res => {
            //直接保存
            this.savePageImageToPhotosAlbum(filePath);
          }).catch(res => {
            //拒绝授权,打开设置
            this.openPhotosAlbumSetting(res);
          });
        } else {
          //3.写入相册
          this.savePageImageToPhotosAlbum(filePath);
        }
      }).catch(res => {
        common.log(res);
      });
    } else {
      common.showModal("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。");
    }
  },

  //提示打开相册权限
  openPhotosAlbumSetting: function (res, filePath) {
    //授权拒绝
    var firstAuthDeny = res.errMsg.indexOf("fail auth deny") != -1;
    if (firstAuthDeny) return;
    //提示打开设置
    common.showModal("亲，我们未获得您的相册授权，即将打开设置", {
      title: '',
      showCancel: true,
    }, () => {
      wx.openSetting({
        success: response => {
          var isOpenWriteAuth = response.authSetting['scope.writePhotosAlbum'];
          if (isOpenWriteAuth) {
            this.savePageImageToPhotosAlbum(filePath);
          }
        }
      })
    })
  },
  //保存图片到相册
  savePageImageToPhotosAlbum: function (filePath) {
    wx.saveImageToPhotosAlbum({
      filePath,
      success: res => {
        common.showToast("保存成功！");
      }
    });
  },
  // 退出
  onLogout() {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/index'
      })
    } else {
      userUtils.removeToken();
      userUtils.removeUserInfo();
      wx.redirectTo({
        url: '/pages/login/index'
      });
    }
  }
})
